﻿using System;
using System.Xml.Linq;

namespace SHomeWorkshop.LunarPresentation.Commands
{
    public partial class Command
    {
        public static void UpdateRecentlyFilesList(string filename)
        {//加入“最近文档”列表。
            if (Globals.MainWindow.miRecentlyFiles.Items.Count >= 10)
            {
                Globals.MainWindow.miRecentlyFiles.Items.RemoveAt(
                    Globals.MainWindow.miRecentlyFiles.Items.Count - 1);
            }

            int repeatIndex = -1;
            foreach (System.Windows.Controls.MenuItem mi in Globals.MainWindow.miRecentlyFiles.Items)
            {
                if (mi.ToolTip.ToString() == filename)
                {
                    repeatIndex = Globals.MainWindow.miRecentlyFiles.Items.IndexOf(mi);
                }
            }

            if (repeatIndex < 0)
            {
                System.Windows.Controls.MenuItem newItem = new System.Windows.Controls.MenuItem()
                {
                    Header = Editor.GetShortFilenameFromFullname(filename),
                    ToolTip = filename
                };

                newItem.Click += new System.Windows.RoutedEventHandler(newItem_Click);

                Globals.MainWindow.miRecentlyFiles.Items.Insert(0, newItem);
            }
            else
            {
                //如果有重复的，则直接调整位置而不是加入新项。
                Object oldItem = Globals.MainWindow.miRecentlyFiles.Items.GetItemAt(repeatIndex);
                Globals.MainWindow.miRecentlyFiles.Items.RemoveAt(repeatIndex);
                Globals.MainWindow.miRecentlyFiles.Items.Insert(0, oldItem);
            }

            WriteToRecentlyFilesListXmlFile();
        }

        public static void WriteToRecentlyFilesListXmlFile()
        {
            XDocument xDoc = new XDocument();
            XElement root = new XElement("RecentlyFiles");
            xDoc.Add(root);

            foreach (System.Windows.Controls.MenuItem mi in Globals.MainWindow.miRecentlyFiles.Items)
            {
                xDoc.Root.Add(new XElement("File") { Value = mi.ToolTip.ToString() });
            }

            xDoc.Save(Globals.pathOfRecentlyFiles);
        }

        static void newItem_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Globals.MainWindow.newItem_Click(sender, e);
        }
    }
}
